package cn.fl.project.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysOrgApiService;
import cmm.user.facade.system.dto.SysOrgDTO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.prjsteprebate.service.IPrjStepRebateApiService;
import cn.fl.project.api.IPrjRbtbillApplyApiService;
import cn.fl.project.condition.PrjRbtbillApplyQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.dto.PrjRbtbillApplyDTO;
import cn.fl.project.service.IPrjRbtbillApplyService;
import cn.fl.project.transform.PrjRbtbillApplyVOTransform;
import cn.fl.project.vo.PrjRbtbillApplyVO;
import com.alibaba.fastjson.JSON;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 返利开票申请表-针对支付表 客户端服务层接口实现
 * 业务层方法名称前缀：
 * 新增：add*
 * 删除：remove*
 * 修改：modify*
 * 批量：batch*
 * 查询对象：select* get*
 * 查询集合：search*
 */
@Service
public class PrjRbtbillApplyServiceImpl implements IPrjRbtbillApplyService {

	/**
     * 日志
     */
    @SuppressWarnings("unused")
    private static final Logger logger = LoggerFactory.getLogger(PrjRbtbillApplyServiceImpl.class);
	
	/**
	 * 返利开票申请表-针对支付表 暴露服务
	 */
	@Autowired
	private IPrjRbtbillApplyApiService prjRbtbillApplyApiService;
	/**
     * 数据字典服务
     */
    @Autowired
    private ISysDictionaryApiService sysDictionaryApiService;
    @Autowired
	private ISysOrgApiService sysOrgApiService;// 组织机构

    @Autowired
    private IPrjStepRebateApiService iPrjStepRebateApiService;

	@Override
	public PrjRbtbillApplyVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)) return null;
		PrjRbtbillApplyDTO dto = this.prjRbtbillApplyApiService.selectPrjRbtbillApplyById(id);
		return PrjRbtbillApplyVOTransform.toVO(dto);
	}

	@Override
	public Long add(PrjRbtbillApplyVO entity) throws BaseException{
		if(null == entity) return null;
		return this.prjRbtbillApplyApiService.addPrjRbtbillApply(PrjRbtbillApplyVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeByIds(List<Long> ids) throws BaseException{
		if(CollectionUtils.isEmpty(ids)) return false;
		return this.prjRbtbillApplyApiService.removePrjRbtbillApplyByIds(ids,CurrentThreadContext.getCurrentUserId());
	}

	@Override
	public boolean modify(PrjRbtbillApplyVO entity) throws BaseException{
		if(null == entity) return false;
		return this.prjRbtbillApplyApiService.modifyPrjRbtbillApply(PrjRbtbillApplyVOTransform.toDTO(entity));
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
        PrjRbtbillApplyQueryCondition condition=null;
        if(null == page) {
            page = new Pager();
            page.setCondition(new PrjRbtbillApplyQueryCondition());
        }
		condition=(PrjRbtbillApplyQueryCondition)page.getCondition();
        condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
        condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
        condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		page=this.prjRbtbillApplyApiService.searchPrjRbtbillApplyListPage(page);
		if(CollectionUtils.isNotEmpty(page.getResultList())){
            List<PrjRbtbillApplyVO> voList=PrjRbtbillApplyVOTransform.toVOList((List<PrjRbtbillApplyDTO>)page.getResultList());
            for (PrjRbtbillApplyVO vo : voList ) {
            	SysOrgDTO buOrgCd = this.sysOrgApiService.selectSysOrgByOrgCd(vo.getBuOrgCd(), CurrentThreadContext.getCurrentSysCd());
            	vo.setBuOrgNm(buOrgCd.getOrgDispNm());
			}
            this.setDictData(voList);
            page.setResultList(voList);
        }
        return page;
	}
	
	@Override
	public List<PrjRbtbillApplyVO> searchList(PrjRbtbillApplyQueryCondition condition) throws BaseException{
		if(null == condition) condition=new PrjRbtbillApplyQueryCondition();
		condition.setSysCd(CurrentThreadContext.getCurrentSysCd());//当前系统代码
		condition.setOrgCd(CurrentThreadContext.getCurrentOrgCd());//当前机构代码
		condition.setUsrId(CurrentThreadContext.getCurrentUserId());//当前用户ID
		List<PrjRbtbillApplyVO> voList=PrjRbtbillApplyVOTransform.toVOList(this.prjRbtbillApplyApiService.searchPrjRbtbillApplyList(condition));
		this.setDictData(voList);
		return voList;
	}
	
    /**
     * 添加数据字典名称
     * @param voList
     */
	public void setDictData(List<PrjRbtbillApplyVO> voList){
		if(CollectionUtils.isEmpty(voList)) return;
		Map<String, String> audStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), "PRJ0096");
		for(PrjRbtbillApplyVO vo:voList){
			if (audStsCdMap != null && audStsCdMap.containsKey(vo.getAudStsCd())) {
            	vo.setAudStsNm(audStsCdMap.get(vo.getAudStsCd()));
        	}	
		}
	}
	
	/**
     * 查询数据字典
     * @param groupCd 组代码
     * @return List<KeyValueVO>
     */
    public List<KeyValueVO> searchCdList(String groupCd){
        return this.sysDictionaryApiService.getKvList(groupCd, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
    }

	@Override
	public DataResultVO addFlowStart(Long bizId, DataResultVO result)
			throws BaseException {
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		//flowStartParamsDTO.setProcDefKey(procDefKey);
		flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
		flowStartParamsDTO.setWordsInTheTable(PrjBscInfoConstant.PRJ_FLOW_S_H_PRJ);
		flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
		flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
		flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
		flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
		flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);
		flowStartParamsDTO.setBusinessType(FlowConstant.FLOW_BUSINESS_TYP_RBT_BILL);
		flowStartParamsDTO.setModelTyp(FlowConstant.FLOW_MODEL_TYP_RBT_BILL);
		flowStartParamsDTO.setBusinessKey(String.valueOf(bizId));
		
		DataResultDTO dataResultDTO = this.prjRbtbillApplyApiService.addFlowStart(flowStartParamsDTO);
		if (dataResultDTO != null) {
			result = new DataResultVO(Integer.parseInt(dataResultDTO.getCode()), dataResultDTO.getInfo());
		} else {
			result = new DataResultVO(BaseConstant.IS_YESNO_NO, "流程发起失败");
		}
		return result;
		
	}

	@Override
	public List<KeyValueVO> getAudStsCdList() throws BaseException {
		String code = "PRJ0096";
		return this.getKeyValueList(code);
	}

	public List<KeyValueVO> getKeyValueList(String code) throws BaseException {
		List<KeyValueVO> keyValueList = null;
		List<SysDictionaryDTO> dictionaryList = this.sysDictionaryApiService
				.searchGroup(CurrentThreadContext.getCurrentSysCd(),
						CurrentThreadContext.getCurrentOrgCd(), code);
		if (CollectionUtils.isNotEmpty(dictionaryList)) {
			keyValueList = new ArrayList<>();
			for (SysDictionaryDTO sysDictionaryDTO : dictionaryList) {
				KeyValueVO keyValue = new KeyValueVO();
				keyValue.setKey(sysDictionaryDTO.getCode());
				keyValue.setValue(sysDictionaryDTO.getCodeNm());
				keyValueList.add(keyValue);
			}
		}
		return keyValueList;
	}

    @Override
    public boolean getStepRebateStateByPaySchNos(List<String> paySchNos) throws BaseException {
        if (CollectionUtils.isEmpty(paySchNos)) {
            throw new BaseException("支付表号集合不能为空");
        }
        BaseLogUtils.newLogger("查询支付表阶梯返利状态参数").setKeys("paySchNos:" + JSON.toJSONString(paySchNos)).info();
        Map<String, Map<String, String>> stepRebateStateByPaySchNos = iPrjStepRebateApiService.getStepRebateStateByPaySchNos(paySchNos);
        BaseLogUtils.newLogger("查询支付表阶梯返利状态结果").setKeys("stepRebateStateByPaySchNos:" + JSON.toJSONString(stepRebateStateByPaySchNos)).info();
        boolean result = true;
        if (CollectionUtils.isMapNotEmpty(stepRebateStateByPaySchNos)) {
            for(Map.Entry<String, Map<String, String>> entry : stepRebateStateByPaySchNos.entrySet()){
                String applyState = entry.getValue().get("applyState");
                String isValid = entry.getValue().get("isValid");
                if (("1".equals(isValid) && ("0".equals(applyState) || "1".equals(applyState) || "2".equals(applyState) || "4".equals(applyState))) || "5".equals(applyState)) {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

}
